package com.qys.livesMall.shop.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.shop.modal.entity.ShopGoodsInfo;
import com.qys.livesMall.shop.modal.entity.ShopGoodsSku;
import com.qys.livesMall.shop.modal.entity.ShopGoodsSkuStocks;
import com.qys.livesMall.shop.service.ShopGoodsInfoService;
import com.qys.livesMall.shop.service.ShopGoodsSkuService;
import com.qys.livesMall.shop.service.ShopGoodsSkuStocksService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * sku库存 前端控制器
 * </p>
 *
 * @author gmx
 * @since 2023-06-07
 */
@RestController
@RequestMapping("/app/shopGoodsSku")
@Tag(name = "App-商铺sku信息", description = "App-sku信息")
public class AppShopGoodsSkuController {

    @Resource
    ShopGoodsSkuService skuService;
    @Resource
    ShopGoodsSkuStocksService stocksService;
    @Resource
    ShopGoodsInfoService infoService;
    @PostMapping("/page/{shopId}")
    @Operation(summary = "sku信息分页")
    public R<Page<ShopGoodsSku>> pagelist(@PathVariable Long shopId, @RequestBody Page<ShopGoodsSku> page){
        LambdaQueryWrapper<ShopGoodsSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsSku::getShopId,shopId);
        Page<ShopGoodsSku> skus = skuService.page(page, queryWrapper);
        List<ShopGoodsSku> skuList = skus.getRecords();
        List<ShopGoodsSku> upSkuList = skuList.stream().map(sku -> {
                    LambdaQueryWrapper<ShopGoodsSkuStocks> stocksQueryWrapper = new LambdaQueryWrapper<>();
                    stocksQueryWrapper.eq(ShopGoodsSkuStocks::getSkuId, sku.getId());
                    stocksQueryWrapper.eq(ShopGoodsSkuStocks::getState,false);
                    stocksQueryWrapper.ne(ShopGoodsSkuStocks::getNum, 0);
                    ShopGoodsInfo goodInfo = infoService.getById(sku.getShopGoodsId());
                    sku.setGoodsName(goodInfo.getGoodsName());
                    sku.setSkuName(sku.getSkuName());
                    List<ShopGoodsSkuStocks> stocks = stocksService.list(stocksQueryWrapper);
                    int nums = stocks.stream().mapToInt(ShopGoodsSkuStocks::getNum).sum();
                    sku.setTotalNum(nums);
                    sku.setPrice(stocks.get(0).getPrice());
                    sku.setCreateTime(stocks.get(0).getCreateTime());
                    return sku;
                })
                .collect(Collectors.toList());
        skus.setRecords(upSkuList);
        return R.ok(skus);
    }
}
